package com.cqcetbbs.smartlab.cqcetbbs.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.cqcetbbs.smartlab.cqcetbbs.R;
import com.cqcetbbs.smartlab.cqcetbbs.javabean.SearchInfo;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by user on 2017/10/27.
 */

public class SearchActivity extends Activity implements View.OnClickListener {

    private static final int SEARCH_SUCCESS = 8;
    private static final int SEARCH_FAIL = 9;
    public static String SEARCH_PATH = "http://api.cqcetlab.com/Home/article/search";
    // 1. 初始化搜索框变量
    private Button btn_search;
    private EditText et_search_content;
    private ImageView iv_back;
    private ListView lv_result;
    ProgressDialog dialog;
    SearchInfo SearchInfo;
    ArrayList<SearchInfo.SearchData> SearchInfos;
    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SEARCH_SUCCESS:
                    final Bundle bundle = msg.getData();
                    String result = bundle.getString("result");
                    if (result.contains("\"\"")) {

                        lv_result.setAdapter(new ArrayAdapter<String>(SearchActivity.this, R.layout.lv_comment_item, R.id.tv_content, new String[]{"没有相关信息"}));
                    } else {

                        Gson gson = new Gson();
                        SearchInfo = gson.fromJson(result, SearchInfo.class);
                        SearchInfos = SearchInfo.getData();
                        String[] str = new String[SearchInfo.getData().size()];
                        for (int i = 0; i < SearchInfo.getData().size(); i++) {
                            str[i] = SearchInfo.getData().get(i).getTitle();
                        }
                        lv_result.setAdapter(new ArrayAdapter<String>(SearchActivity.this, R.layout.lv_comment_item, R.id.tv_content, str));

                        lv_result.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                Intent intent = new Intent(SearchActivity.this, NewsDetailActivity.class);
                                Bundle newsBundle = new Bundle();
                                newsBundle.putString("id",SearchInfos.get(i).getArticle_id());
                                intent.putExtras(newsBundle);
                                startActivity(intent);
                            }
                        });
                    }
                    dialog.dismiss();
                    break;
                case SEARCH_FAIL:
                    Toast.makeText(SearchActivity.this, "搜索失败", Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
    }

    private void initView() {
        btn_search = findViewById(R.id.btn_search);
        et_search_content = findViewById(R.id.et_search_content);
        iv_back = findViewById(R.id.iv_back);
        lv_result = findViewById(R.id.lv_result);
        iv_back.setOnClickListener(this);
        btn_search.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_search:
                String content = et_search_content.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(this, "请输入搜索内容！", Toast.LENGTH_SHORT).show();
                    return;
                }
                showDialog();
                getSearchData(content);
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    private void showDialog() {

        dialog = new ProgressDialog(this);
        dialog.setMessage("搜索中。。。");
        dialog.setCancelable(false);
        dialog.show();
    }

    public void getSearchData(String field) {
        final OkHttpClient client = new OkHttpClient();

        final String inner_field = field;
        final String inner_num = field;

        new Thread(new Runnable() {
            @Override
            public void run() {

                FormBody body = new FormBody.Builder()
                        .add("field", inner_field)
//                        .add("num", inner_num)
                        .build();
                Request request = new Request.Builder()
                        .get()
                        .put(body)
                        .url(SEARCH_PATH)
                        .build();
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        String result = response.body().string();
                        Bundle bundle = new Bundle();
                        bundle.putString("result", result);
                        Log.e("result", result);
                        Message msg = mhandler.obtainMessage(SEARCH_SUCCESS);
                        msg.setData(bundle);
                        mhandler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Message msg = mhandler.obtainMessage(SEARCH_FAIL);
                    mhandler.sendMessage(msg);

                }
            }
        }).start();
    }
}
